# -*- coding: utf8 -*-

from plugmgr import plugin
import twisted, twisted.words, sys, popen2
from twisted.words.xish.domish import Element

__all__ = ['muc']

class muc(plugin):
    requires = ['stanzas','config','cmd','events']
    def __init__(self, bot):
        self.bot = bot
        self.rooms = {}
        self.bot["config"].setdefault('nick', 'Eggrevenger', 0, 100)
        self.bot["config"].setdefault('rooms', '', 0, 100)
        self.bot['cmd'].addHandler('join',self.cmdjoin)
        self.bot['cmd'].addHandler('leave',self.cmdleave)
        self.bot['cmd'].addHandler('rooms',self.cmdrooms)
    def connected(self):
        self.selfFilterId = self.bot['events'].registerHandler('message',self.selfFilter,True)
        for room in self.bot['config']['rooms'].split('\n'):
            room = room.split('/')
            self.join(room[0],'/'.join(room[1:]))
    def unload(self):
        self.bot['cmd'].removeHandler('join')
        self.bot['cmd'].removeHandler('leave')
        self.bot['cmd'].removeHandler('rooms')
        self.bot['events'].removeHandler('message',self.selfFilterId)
    def selfFilter(self,source,type,body,lang):
        if type == 'groupchat':
            source = source.split('/')
            room = source[0]
            nick = '/'.join(source[1:])
            if self.rooms[room] == nick:
                raise StopIteration
    def join(self,room,nick=''):
        if not nick.strip():
            nick = self.bot["config"]['nick']
        jid = u'/'.join((room,nick))
        status = self.bot["config"]["status"]
        msg    = self.bot["config"]["status_msg"]

        p = Element(('jabber:client', 'presence'))
        p['to'] = jid
        p.addElement('show').addContent(status)
        p.addElement('status').addContent(msg)
        p.addElement('x','http://jabber.org/protocol/muc').addElement('history').__setitem__('maxchars', '0')
        # print p.toXml()
        self.bot.stream.send(p)
        self.rooms[room] = nick
        self.bot['config']['rooms'] = '\n'.join('/'.join((room,self.rooms[room])) for room in self.rooms.keys())
    def leave(self,room):
        jid = u'/'.join((room,self.rooms[room]))
        p = Element(('jabber:client', 'presence'))
        p['to'] = jid
        p['type'] = 'unavailable'
        p.addElement('status').addContent(u'Выгнали с позором :\'(')
        self.bot.stream.send(p)
        del self.rooms[room]
        self.bot['config']['rooms'] = '\n'.join('/'.join((room,self.rooms[room])) for room in self.rooms)
    def cmdjoin(self,c):
        a = c.args.strip().split(' ')
        self.join(a[0],' '.join(a[1:]))
        c.reply('Maybe joined')
    def cmdleave(self,c):
        self.leave(c.args.strip())
        c.reply('Maybe leaved')
    def cmdrooms(self,c):
        c.reply('\n'.join(['']+self.rooms.keys()))
    def sendMessage(self,*args):
        self.bot['stanzas'].sendMessage(*args) # TODO: выкинуть это нафиг
    def access(self,jid):
        return 0 # TODO


